import 'dart:developer';
import 'dart:ui';
import 'dart:convert' as convert;
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_xj_video/custom_drawer/drawer_item.dart';
import 'package:flutter_xj_video/entity/film_entity.dart';
import 'package:get/get.dart' as getx;
import 'package:xml2json/xml2json.dart';

class DetailPage extends StatefulWidget {
  @override
  _DetailPageState createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage>
    with SingleTickerProviderStateMixin {
  FilmRssListVideo filmRssListVideo;
  AnimationController _animationController;

  bool isOpenx = false;
  Size screenSize;
  double detailViewHeight = 450;
  double imageMarginTop = 60;
  List urls = [];
  DrawerItem drawerItem;

  ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    filmRssListVideo = getx.Get.arguments[0];
    drawerItem = getx.Get.arguments[1];
    log(filmRssListVideo.dl.dd);
    var j = filmRssListVideo.dl.dd.split('\$');
    log('j:' + j.toString());
    for (var i = 0; i < j.length; i++) {
      if (j[i].indexOf('.m3u8') >= 0 && j[i].startsWith('http')) {
        urls.add(j[i]);
      }
    }
    loadData(filmRssListVideo, drawerItem);
    _animationController = AnimationController(
        duration: const Duration(milliseconds: 100), vsync: this);
    super.initState();
    _scrollController.addListener(() {
      setState(() {
        detailViewHeight -= _scrollController.offset;
        if (detailViewHeight < 280) {
          detailViewHeight = 280;
        }
        if (detailViewHeight > 450) {
          detailViewHeight = 450;
        }
        if (detailViewHeight == 280) {
          _animationController.forward();
        } else {
          _animationController.reverse();
        }
        // print("高度" + ((detailViewHeight - 280) / 170).toString());
      });
    });
    _animationController.addStatusListener((status) {
      if (status == AnimationStatus.forward) {
        imageMarginTop = 10;
      } else if (status == AnimationStatus.reverse) {
        imageMarginTop = 60;
      }
    });
  }

  loadData(FilmRssListVideo video, DrawerItem item) async {
    Response response;
    var dio = Dio();
    dio.options.contentType = Headers.jsonContentType;
    dio.options.responseType = ResponseType.plain;
    var url = item.api + '?ac=videolist&ids=' + video.id;
    response = await dio.post(url);
    final myTransformer = Xml2Json();
    myTransformer.parse(response.data.toString());
    var filmJson = myTransformer.toParker();
    Map<String, dynamic> jsonMap = convert.jsonDecode(filmJson);
    FilmRssListVideo videox =
        FilmRssListVideo().fromJson(jsonMap['rss']['list']['video']);
    urls = [];
    var j = videox.dl.dd.replaceAll("#", '\$').split('\$');
    for (var i = 0; i < j.length; i++) {
      if (j[i].length < 10) {
        j.removeAt(i);
      }
    }

    for (var i = 0; i < j.length; i++) {
      if (j[i].indexOf('.m3u8') >= 0 && j[i].startsWith('http')) {
        urls.add(j[i]);
      }
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    screenSize = MediaQuery.of(context).size;
    return Scaffold(
      body: Container(
        height: 1500,
        child: Stack(
          children: [
            Container(
                child: Image.network(
              filmRssListVideo.pic,
              width: screenSize.width,
              fit: BoxFit.fill,
            )),
            BackdropFilter(
              filter: ImageFilter.blur(sigmaX: 5.0, sigmaY: 5.0),
              child: Center(
                child: Container(
                  child: Text("."),
                  // color: Colors.red,
                ),
              ),
            ),
            AnimatedPositioned(
              duration: Duration(microseconds: 1000),
              curve: Curves.linear,
              top: imageMarginTop,
              left: 80,
              right: 80,
              child: ScaleTransition(
                alignment: Alignment.center,
                scale: new Tween(begin: 1.0, end: 0.5)
                    .animate(_animationController),
                child: Container(
                  decoration: BoxDecoration(
                      image: DecorationImage(
                          image: NetworkImage(filmRssListVideo.pic),
                          fit: BoxFit.fill),
                      border: Border.all(
                          color: Colors.white,
                          width: 3,
                          style: BorderStyle.solid)),
                  height: 300,
                  width: 100,
                ),
              ),
            ),
            Positioned(
                top: detailViewHeight,
                bottom: 0,
                child: SingleChildScrollView(
                    controller: _scrollController,
                    child: detailContentWidget(filmRssListVideo))),
            Positioned(
                top: 40,
                left: 15,
                child: GestureDetector(
                    onTap: () {
                      getx.Get.back();
                    },
                    child:
                        Icon(Icons.arrow_back, color: Colors.white, size: 30)))
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _animationController.dispose();
  }

  Widget detailContentWidget(FilmRssListVideo video) {
    return Container(
      padding: EdgeInsets.all(15),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(topRight: Radius.circular(20))),
      width: screenSize.width,
      constraints: BoxConstraints(minHeight: screenSize.height / 2 + 200),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: const EdgeInsets.only(top: 5, right: 5),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Icon(
                  Icons.star_outline,
                  size: 44,
                  color: Colors.grey,
                ),
                GestureDetector(
                  onTap: () {
                    log(urls.toString());
                    if (urls.length == 0) {
                      log("未获取到资源");
                      return;
                    }
                    if (urls.length > 1) {
                      showModalBottomSheet(
                          context: context,
                          builder: (context) {
                            return ListView.builder(
                                itemCount: urls.length,
                                itemBuilder: (context, index) {
                                  return ListTile(
                                    leading: Icon(Icons.play_circle_fill),
                                    title: Text('第${index + 1}集'),
                                    onTap: () {
                                      video.dl.dd = urls[index];
                                      getx.Get.back();
                                      getx.Get.toNamed("/play",
                                          arguments: video);
                                    },
                                  );
                                });
                          });
                    } else {
                      video.dl.dd = urls[0];
                      getx.Get.back();
                      getx.Get.toNamed("/play", arguments: video);
                    }
                  },
                  child: Icon(
                    Icons.play_circle_outline,
                    size: 44,
                  ),
                ),
              ],
            ),
          ),
          Text(
            video.name,
            style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
          ),
          SizedBox(
            height: 5,
          ),
          Row(
            children: [
              Text(video.area +
                  ' | ' +
                  video.lang +
                  ' | ' +
                  video.area +
                  ' | ' +
                  video.year +
                  ' | ' +
                  video.note),
            ],
          ),
          SizedBox(
            height: 5,
          ),
          Text('导演：' + video.director),
          SizedBox(
            height: 5,
          ),
          Text('演员：' + video.actor),
          SizedBox(
            height: 5,
          ),
          Text('简介：\n' + video.des),
        ],
      ),
    );
  }
}

/**
 * 
*/
